package cn.com.wxd.action.admin.website;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.wxd.action.AjaxResult;
import cn.com.wxd.action.ValidatorResult;
import cn.com.wxd.biz.website.CatalogService;
import cn.com.wxd.biz.website.WebsiteCache;
import cn.com.wxd.entity.website.CatalogInfo;
import cn.com.wxd.common.data.KeyValue;
import cn.com.wxd.util.website.CatalogTree;
import cn.com.wxd.util.website.CatalogTreeEntity;
import cn.com.wxd.util.website.WebsiteInfo;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/7/5.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/admin/website/catalog")
public class CatalogCtl {

    @Resource
    private CatalogService catalogService;

    /**
     * 栏目树页面
     *
     * @param caid
     * @param map
     *
     * @return
     */
    @RequestMapping("/catalogTree")
    public String catalogTree(@RequestParam(required = false) String caid, ModelMap map) {
        String catalogTreeDom;
        List<CatalogInfo> allCatalogs = catalogService.getAllCatalog(new HashMap<String, String>());
        map.put("allCatalogs", allCatalogs);
        map.put("caid", caid);
        if (WebsiteInfo.isCache()) {
            // 先从缓存中获取
            Object catalogTreeDomo = WebsiteCache.getWebsiteObjectCache("catalogTreeDom");
            if (catalogTreeDomo != null && !catalogTreeDomo.equals("")) {
                catalogTreeDom = String.valueOf(catalogTreeDomo);
                map.put("catalogTreeDom", catalogTreeDom);
                return "/admin/website/catalog/catalog";
            }
        }
        CatalogTree ct = new CatalogTree(allCatalogs);
        catalogTreeDom = ct.getCatalogTreeHTML(new CatalogTreeEntity());
        if (WebsiteInfo.isCache()) {
            // 放入缓存
            WebsiteCache.setWebsiteObjectCache("catalogTreeDom", catalogTreeDom);
        }
        map.put("catalogTreeDom", catalogTreeDom);
        return "/admin/website/catalog/catalog";
    }

    /**
     * 获取子栏目列表
     *
     * @param parentId
     *
     * @return
     */
    @RequestMapping("/cataloglist")
    public String catalogList(String parentId, ModelMap map) {
        String cataNav;
        List<CatalogInfo> subCatalogs;
        if (parentId == null || parentId.equals("") || parentId.equalsIgnoreCase("root")) {
            parentId = "";
            cataNav = "根栏目";
            subCatalogs = catalogService.getRootCatalog();
        } else {
            List<KeyValue<Integer, String>> list = catalogService.getCatalogNav(parentId);  //设置导航栏字符串
            cataNav = "";
            for (int i = list.size() - 1; i >= 0; i--) {
                if (cataNav.equals("")) {
                    cataNav = list.get(i).getValue();
                    continue;
                }
                cataNav += " > " + list.get(i).getValue();
            }
            subCatalogs = catalogService.getSubCatalog(parentId);
        }
        map.put("parentId", parentId);
        map.put("cataNav", cataNav);
        map.put("subCatalogs", subCatalogs);
        return "/admin/website/catalog/cataloglist";
    }

    /**
     * 添加catalog页面
     *
     * @return
     */
    @RequestMapping("/addCatalog")
    public String addCatalog(String parentId, ModelMap map) {
        map.put("parentId", parentId);
        return "/admin/website/catalog/addcatalog";
    }

    /**
     * 编辑catalog页面
     *
     * @return
     */
    @RequestMapping("/editCatalog")
    public String editCatalog(String id, ModelMap map) {
        map.put("actionType", "update");
        CatalogInfo catalogInfo = catalogService.getCatalogById(id);
        if (catalogInfo == null) {
            map.put("actionError", "数据获取失败!");
            return "redirect:/admin/website/catalog/catalogList";
        }
        map.put("parentId", catalogInfo.getParentId());
        map.put("catalogInfo", catalogInfo);
        return "/admin/website/catalog/addcatalog";
    }

    /**
     * 保存catalog
     *
     * @return
     */
    @RequestMapping(value = "/saveCatalog", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult saveCatalog(CatalogInfo catalogInfo, String actionType) {
        ValidatorResult validatorResult = CatalogCtlValidator.saveCatalogValidat(catalogInfo);
        if (validatorResult.isFailure()) {
            return AjaxResult.failureResult(validatorResult.getMessage());
        }
        if (actionType != null && !actionType.equalsIgnoreCase("update")) {
            if (catalogService.isExistCataCode(catalogInfo.getCataCode())) {
                return AjaxResult.failureResult("栏目标识号已经存在!");
            }
        }
        if (!catalogService.addCatalog(catalogInfo)) {
            return AjaxResult.failureResult("添加失败!");
        }
        return AjaxResult.successResult("caid");
    }

    @RequestMapping("/deleteCatalog")
    @ResponseBody
    public AjaxResult deleteCatalog(String id) {
        //"栏目下是否存在文章或子栏目"
        if (!catalogService.isExistArt(id) && !catalogService.isExistCata(id)) {
            if (catalogService.deleteCatalog(id)) {
                return AjaxResult.successResult();
            } else {
                return AjaxResult.errorResult("未知原因，删除失败!", new Exception("未知原因，删除失败!"));
            }
        } else {
            return AjaxResult.failureResult("该栏目下有文章，现在无法删除!");
        }
    }

    /**
     * 栏目的排序
     *
     * @return
     */
    @RequestMapping("/catalogSorting")
    @ResponseBody
    public AjaxResult catalogSorting(String newOrdId, String oldOrdId) {
        if (catalogService.rankCatalog(newOrdId, oldOrdId)) {
            return AjaxResult.successResult();
        } else {
            return AjaxResult.failureResult("排序失败!");
        }
    }

    /**
     * 初始化了articleInfo的参数绑定前缀
     *
     * @param binder
     */
    @InitBinder("catalogInfo")
    public void initBinderCatalogInfo(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("catalogInfo.");
    }
}
